package utils

import (
	"errors"
	"net"
)

var ERR_NO_LOCAL_IP_FOUND = errors.New("没有找到网卡IP")

// 获取本机网卡IP
func GetLocalIP() (ipv4 string, err error) {
	// 获取所有网卡
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()

			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						ipv4 = ipnet.IP.String()
						return
					}
				}
			}
		}
	}

	err = ERR_NO_LOCAL_IP_FOUND
	return
}
